<?php

namespace Modules\Customer\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Catch\Exceptions\FailedException;
use Illuminate\Http\Request;
use Modules\Configuration\Models\Configuration;
use Modules\Customer\Models\Customer;
use Modules\CustomerLesson\Models\CustomerLesson;
use Modules\LessonHour\Http\Controllers\LessonHourController;
use Modules\LessonTime\Models\LessonTime;
use Modules\Notice\Models\Notice;
use Modules\Reservation\Models\Reservation;
use Modules\Teacher\Models\Teacher;
use Modules\TeacherLesson\Models\TeacherLesson;

class HomeController extends Controller
{
    public function __construct(
        protected readonly Customer $model
    ){}

    public function getLoginCustomer(Request $request)
    {
        $tokens = $request->header('token');
        $customer = Customer::query()->where('unique_id',$tokens)->first();

        if (empty($customer) || $customer['status'] == 0)
        {
            throw new FailedException("请重新登录",'401');
        }

        return $customer;
    }

    /**
     * 首页
     * @param Request $request
     * @return array
     */
    public function homePage(Request $request)
    {
        $result = [];
        $notice = Notice::query()->select(['id',"title","image","created_at"])->orderBy('id', 'desc')->limit(5)->get();
        $banner = Configuration::query()->where('id',1)->select('banners')->first();

        $customer = $this->getLoginCustomer($request);
        $reservation = Reservation::query()->where(['customer_id',$customer['id']])->first();

        $result['notice'] = $notice;
        $result['banner'] = isset($banner['banners']) ? explode("," ,$banner['banners']) : [];
        $result['reserve'] = !empty($reservation);

        return $result;
    }

    /**
     * 公告列表
     * @param Request $request
     * @return mixed
     */
    public function noticeList(Request $request)
    {
        $param = $request->all();
        return Notice::query()->select(['id',"title","image","created_at"])->orderBy('id', 'desc')->paginate($param['limit'] ?? 10 ,['*'] ,'' ,$param['page'])->toArray();
    }

    /**
     * 公告详情
     * @param Request $request
     * @return mixed
     */
    public function noticeInfo(Request $request)
    {
        $id = $request->get('id');
        return Notice::query()->select(['id',"title","content","image","created_at"])->find($id);
    }


    /**
     * 获取老师列表
     * @param Request $request
     * @return array
     */
    public function teacherList(Request $request)
    {
        $result = [];
        $subjectId = $request->get('subject_id');
        $customerId= $this->getLoginCustomer($request)['id'];

        $customerLessons = CustomerLesson::query()
            ->where('customer_lesson.customer_id',$customerId)
            ->select(['customer_lesson.teacher_id','teacher.name','teacher.subject_id'])
            ->join('teacher','teacher.id','=','customer_lessons.teacher_id')
            ->orderBy('customer_lesson.lessons','desc')
            ->get();

        if (!empty($customerLessons))
        {
            foreach ($customerLessons as $customerLesson)
            {
                $subjectIds = explode(",",$customerLesson['subject_id']);
                if (in_array($subjectId,$subjectIds))
                {
                    $result[] = [
                        'teacher_id' => $customerLesson['teacher_id'],
                        'teacher_name' => $customerLesson['name'],
                        'last_lessons' => $customerLesson['lessons'] ?? 0,
                    ];
                }
            }
        }

        return $result;
    }


    /**
     * 获取老师详情
     * @param Request $request
     * @return mixed
     */
    public function teacherInfo(Request $request)
    {
        $teacherId = $request->get('teacher_id');
        $customerId = $this->getLoginCustomer($request)['id'];

        $lessonData = Teacher::query()->select(['teacher.id as teacher_id','teacher.name as teacher_name','customer_lesson.lessons'])
            ->join("customer_lesson","customer_lesson.teacher_id","=","teacher.id")
            ->where(["teacher.id" => $teacherId,'customer_id' => $customerId])->first();

        return $lessonData;
    }

    // 教师课程时间

    public function teacherLessonTime(Request $request)
    {
        $teacherId = $request->get('teacher_id');
        $customerId = $this->getLoginCustomer($request)['id'];

        $teacher = Teacher::query()->find($teacherId);
        if (empty($teacher))
        {
            throw new FailedException("老师不存在");
        }

        $lessonData = CustomerLesson::query()->where(['customer_id' => $customerId,'teacher_id' => $teacherId])->first();
        if (empty($lessonData))
        {
            throw new FailedException("未购买该老师课程");
        }

        $depDate = date("Y-m-d");
        $arrDate = date("Y-m-d",strtotime($depDate . "+6 day"));

        $reserveStatus = [LessonHourController::LESSON_STATUS_1,LessonHourController::LESSON_STATUS_2,LessonHourController::RESERVATION_4];
        $reservationLt = Reservation::query()->where('teacher_id', $teacherId)->whereIn('status', $reserveStatus)->whereBetween('lesson_date',[$depDate, $arrDate])->get();
        $reserveCounts = $this->getReserveCount($reservationLt);

        $lessonTimeIds = explode(",",$lessonData['lesson_time_ids']);
        $lessonTimeArr = $this->arrayColumn(LessonTime::query()->select(['id','start_time','end_time','time_long'])->get(),"id");
        $teacherLesson = $this->arrayColumn(TeacherLesson::query()->select(['lesson_date','lesson_time_ids'])->where(['teacher_id' => $teacherId])->whereBetween('lesson_date',[$depDate, $arrDate])->get(),"lesson_date");
        $systemLessons = Configuration::query()->where('id',1)->select('lessons')->first();

        $today = date("Y-m-d");

        // status 1:可约，2：约满，3：结束
        for ($i = 0; $i < 7; $i++)
        {
            $date = date("Y-m-d",strtotime($depDate . "+$i day"));
            $result[$i]['date'] = date("m-d",strtotime($date));
            $result[$i]['week'] = date("w",strtotime($date)) == 0 ? "周日" : $this->translateWeek(date("w",strtotime($date)));
            $result[$i]['status'] = 1;

            // 当天老师课表及是否约满
            $dateLesson = isset($teacherLesson[$date]) ? explode(",",$teacherLesson[$date]['lesson_time_ids']) : (isset($systemLessons['lessons']) ? explode(",",$systemLessons['lessons']) : array_keys($lessonTimeArr));
            if (isset($reserveCounts[$date]) && $reserveCounts[$date] >= count($dateLesson))
            {
                $result[$i]['status'] = 2;
            }
            elseif ($today == $date)
            {
                $nowTime = date("H:i:s");
                foreach ($dateLesson as $lessonTimeId)
                {
                    if ($nowTime > $lessonTimeArr[$lessonTimeId]['start_time'] && $nowTime < $lessonTimeArr[$lessonTimeId]['end_time'])
                    {
                        $result[$i]['status'] = 2;
                        break;
                    }
                }
            }

            foreach ($lessonTimeArr as $lessonTime)
            {
                if (in_array($lessonTime['id'],$lessonTimeIds))
                {
                    $result[$i]['time'][] = [
                        'id' => $lessonTime['id'],
                        'start_time' => $lessonTime['start_time'],
                        'end_time' => $lessonTime['end_time'],
                        'time_long' => $lessonTime['time_long'],
                        'status' => $this->getLessonStatus($reservationLt,$date,$lessonTime['id']),
                    ];
                }
            }
        }

        return $result;
    }

    // 预约课程
    public function reserveLesson(Request $request)
    {
        $teacherId = $request->get('teacher_id');
        $customerId = $this->getLoginCustomer($request)['id'];

        $teacher = Teacher::query()->find($teacherId);
        if (empty($teacher))
        {
            throw new FailedException("老师不存在");
        }

        $customer = Customer::query()->find($customerId);
        if (empty($customer))
        {
            throw new FailedException("用户不存在");
        }

        $reservation = Reservation::query()->where(['customer_id'=>$customerId,'teacher_id'=>$teacherId])->first();
        if (!empty($reservation))
        {
            throw new FailedException("已预约该老师");
        }

        $data = [
            'customer_id' => $customerId,
            'teacher_id' => $teacherId,
            'status' => 1,
        ];

        return Reservation::query()->create($data);
    }

    public function translateWeek($week)
    {
        return $week == 1 ? "周一" : ($week == 2 ? "周二" : ($week == 3 ? "周三" : ($week == 4 ? "周四" : ($week == 5 ? "周五" : ($week == 6 ? "周六" : "周日")))));
    }

    public function arrayColumn($data,$column)
    {
        $result = [];
        foreach ($data as $item)
        {
            $result[$column] = $item;
        }
        return $result;
    }

    public function getReserveCount($data)
    {
        $result = [];
        foreach ($data as $item)
        {
            $result[$item['lesson_date']] += 1;
        }

        return $result;
    }
}
